class Solution {
public:
    bool ForA[10][10] = {false};
    vector<pair<int, int>> Move = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> res;
        if (matrix.size() == 0)
            return res;
        int rows = matrix.size(), cols = matrix[0].size();
        int sum = matrix.size() * matrix[0].size();
        int m = 0;
        int i = 0;
        int j = 0;
        while (sum) {
            if (ForA[i][j] == false) {
                res.push_back(matrix[i][j]);
                ForA[i][j] = true;
                sum--;
            }
            int ni = i + Move[m].first, nj = j + Move[m].second;
            if (ni < 0 || ni >= rows || nj < 0 || nj >= cols || ForA[ni][nj]) {
                m = (m + 1) % 4; // 改变方向
                ni = i + Move[m].first;
                nj = j + Move[m].second;
            }
            i = ni;
            j = nj;
        }
        return res;
    }
};
